﻿using System;
using Duo1JHttpServer.Framework.Interface;
using Duo1JHttpServer.Framework.Model;

namespace Duo1JHttpServer.Framework.Server
{
    /// <summary>
    /// 抽象http请求处理器
    /// </summary>
    public abstract class AbstractHttpHandler : IHttpHandler, IHttpHandle
    {
        protected RequestModel requestModel;

        public void HandleGet()
        {
            if (requestModel == null)
            {
                throw new Exception("RequestModel is NULL!");
            }

            try
            {
                StaticHandler.RequestSuccess(requestModel);
                GetHandler();
            }
            catch (Exception e)
            {
                string errorMsg = $"{e.Message}\n{e.StackTrace}";
                Console.WriteLine(errorMsg);
                StaticHandler.RequestServerError(requestModel.OutputWriter, errorMsg);
            }
        }

        public void HandlePost()
        {
            if (requestModel == null)
            {
                throw new Exception("RequestModel is NULL!");
            }

            try
            {
                StaticHandler.RequestSuccess(requestModel);
                PostHandler();
            }
            catch (Exception e)
            {
                string errorMsg = $"{e.Message}\n{e.StackTrace}";
                Console.WriteLine(errorMsg);
                StaticHandler.RequestServerError(requestModel.OutputWriter, errorMsg);
            }
        }

        public void SetModel(RequestModel requestModel)
        {
            this.requestModel = requestModel ?? throw new Exception("RequestModel is NULL!");
        }

        public abstract void GetHandler();
        public abstract void PostHandler();
    }
}